package com.atfusu.service.impl;


import com.atfusu.bean.entity.Dict;
import com.atfusu.dao.DictDao;
import com.atfusu.service.DictService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title:
 * Author: fusu
 * DateTime:  2022/11/28
 * Description:
 **/
@DubboService
public class DictServiceImpl implements DictService {

    @Autowired
    private DictDao dictDao;


    /**
     * 返回数据格式: [{id:num,isParent:true/false,name:"全部分类等"}]
     */
    @Transactional(readOnly = true)
    @Override
    public List<Map<String, Object>> findZnodes(Long id) {
        //1. 根据父节点获取所有子节点数据
        List<Dict> dicts = dictDao.findByParentId(id);
        //2. 构建ztree格式的数据
        //2.1创建list集合
        List<Map<String, Object>> list = new ArrayList<>();
        for (Dict dict : dicts) {

            Map<String, Object> map = new HashMap<>();
            //查看当前数据是否有子节点
            Integer count = dictDao.countSonByParentId(dict.getId());
            //用于存放每一条数据
            map.put("id", dict.getId());
            map.put("isParent", count > 0);
            map.put("name", dict.getName());
            //把map集合装入list
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Dict> findListByParentId(Long id) {
        List<Dict> dicts = dictDao.findByParentId(id);
        return dicts;
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //根据dictCode=beijing,获取北京的id
        Dict dict = dictDao.getByDictCode(dictCode);
        //再以北京的id做为父级id查询所有子级
        List<Dict> dicts = findListByParentId(dict.getId());
        return dicts;
    }

    @Override
    public String getNameById(Long id) {
        return dictDao.getNameById(id);
    }
}
